package com.campus.counseling.service.impl;

import com.campus.counseling.service.EmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;
    private final StringRedisTemplate redisTemplate;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @Value("${verify.code.expiration}")
    private long codeExpiration;
    
    @Value("${verify.code.length}")
    private int codeLength;

    @Override
    public void sendVerificationCode(String to, String code) {
        // 检查是否存在发送频率限制
        String rateLimitKey = "email_rate_limit:" + to;
        if (Boolean.TRUE.equals(redisTemplate.hasKey(rateLimitKey))) {
            throw new RuntimeException("发送太频繁，请稍后再试");
        }
        
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("校园心理咨询平台 - 重置密码验证码");
            
            String content = String.format(
                "<div style='padding: 20px; background-color: #f8f9fa; border-radius: 5px;'>" +
                "<h3 style='color: #333;'>密码重置验证码</h3>" +
                "<p style='color: #666;'>您的验证码是：</p>" +
                "<h2 style='color: #007bff; letter-spacing: 2px;'>%s</h2>" +
                "<p style='color: #666;'>验证码有效期为5分钟，请尽快使用。</p>" +
                "<p style='color: #999; font-size: 12px; margin-top: 20px;'>如果这不是您的操作，请忽略此邮件。</p>" +
                "</div>",
                code
            );
            
            helper.setText(content, true);
            mailSender.send(message);
            
            // 将验证码保存到Redis，设置过期时间
            String key = "verify_code:" + to;
            redisTemplate.opsForValue().set(key, code, codeExpiration, TimeUnit.SECONDS);
            
            // 设置发送频率限制（60秒内不能重复发送）
            redisTemplate.opsForValue().set(rateLimitKey, "1", 60, TimeUnit.SECONDS);
            
        } catch (MessagingException e) {
            throw new RuntimeException("发送邮件失败", e);
        }
    }

    @Override
    public String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < codeLength; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    @Override
    public boolean verifyCode(String email, String code) {
        String key = "verify_code:" + email;
        String savedCode = redisTemplate.opsForValue().get(key);
        if (savedCode != null && savedCode.equals(code)) {
            redisTemplate.delete(key);
            return true;
        }
        return false;
    }
} 